package stardust.core.support;


public class BitUtils
{

  public static byte[] byteToBit(byte b)
  {
    char[] charOfBit = Integer.toBinaryString(b).toCharArray();
    byte[] bit = new byte[8];

    for (int i = 0; i < bit.length; i++)
    {
      bit[i] = i < bit.length - charOfBit.length ? 0 : (byte) Character.getNumericValue(charOfBit[i - (bit.length - charOfBit.length)]);
    }

    return bit;
  }

  public static byte bitToByte(byte[] b)
  {
    StringBuffer buffer = new StringBuffer(8);

    for (int i = 0; i < b.length; i++)
    {
      buffer.append(b[i]);
    }

    return Byte.parseByte(buffer.toString(), 2);
  }

  public static byte[] getBit(byte b, int offset, int len)
  {
    byte[] bit = byteToBit(b);
    byte[] r = new byte[len];

    System.arraycopy(bit, offset, r, 0, len);

    return r;
  }

  public static byte getBit(byte b, int offset)
  {
    return getBit(b, offset, 1)[0];
  }

  public static byte setBit(byte b, int offset, byte bitValue)
  {
    byte[] bit = byteToBit(b);

    bit[offset] = bitValue;

    return bitToByte(bit);
  }

}
